package dao.connectortodb;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;

public class ConnectorToDB {
	private DistributerProperties distributerProperties;
	private Connection connection = null;
	private Logger log = Logger.getLogger(ConnectorToDB.class);
	private static final String SQL_EXCEPTION = " Database access error";
	private static final String INSTANTIATION_EXCEPTION = "The specified class object cannot be instantiated";
	private static final String ILLEGALACCESS_EXCEPTION = "In the currently executing method does not have access to the definition of the specified class, field, method or constructor";
	private static final String CLASSNOTFOUND_EXCEPTION = "Sorry, class not found";
	private static ConnectorToDB CONNECTOR_TO_DB = null;

	private ConnectorToDB() {
		try{
		distributerProperties = new DistributerProperties();
		Class.forName(distributerProperties.getDriverName()).newInstance();

		} catch (InstantiationException ie) {
		log.error(INSTANTIATION_EXCEPTION);
		} catch (IllegalAccessException iae) {
		log.error(ILLEGALACCESS_EXCEPTION);
		} catch (ClassNotFoundException cnfe) {
		log.error(CLASSNOTFOUND_EXCEPTION);
		}
	}

	public static ConnectorToDB getInstance() {
		if (CONNECTOR_TO_DB == null) {
			CONNECTOR_TO_DB = new ConnectorToDB();
		}
		return CONNECTOR_TO_DB;
	}

	public Connection getConnection() {
		try {

			connection = DriverManager.getConnection(
					distributerProperties.getUrlDriver(),
					distributerProperties.getUser(),
					distributerProperties.getPassword());

		}

		catch (SQLException sqle) {
			log.error(SQL_EXCEPTION);
		}

		return connection;

	}

	

}
